package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import po.Result;
import po.User;
import service.LoginService;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/login")
    public String login() {
        //返回登录界面视图
        return "user/login";
    }

    @RequestMapping("/loginSubmit")
    //登录请求处理
    public @ResponseBody
    String loginSubmit(HttpSession session, String username, String password) throws Exception {
        User user = new User();
        user.setNumber(username);
        user.setPassword(password);
        return loginService.login(user, session);
    }

    @RequestMapping("/logout")
    //登出请求处理
    public String logout(HttpSession session) {
        session.invalidate();
        //登出之后返回到登录界面
        return "redirect:login";
    }

    @RequestMapping("/index")
    public String index(HttpSession session) {
        //如果用户未登录就进行拦截，重定向到登录界面
        if (session.getAttribute("userName") == null) {
            return "redirect:login";
        } else {
            //如果已经登录，则返回主界面视图
            return "user/index";
        }
    }

    @RequestMapping("/getUpdatePwdView")
    //返回修改密码界面视图
    public String getUpdatePwdView() {
        return "user/updatePwd";
    }

    @RequestMapping("/updatePwd")
    //修改密码请求处理
    public @ResponseBody
    Result updatePwd(HttpSession session, String oldPwd, String newPwd) throws Exception {
        return loginService.updatePwd((String) session.getAttribute("userNumber"), oldPwd, newPwd);
    }
}
